const todoState = {
    todos:JSON.parse(localStorage.getItem("todo")) || [],  // 源数据
    showTodo:JSON.parse(localStorage.getItem("todo")) || [],
}

export function todoReducer(state=todoState,action){
    console.log(action);
    switch (action.type) {
        // 添加
        case "ADDTODO":
            var flag = false;
            state.todos.forEach(element=>{
                if(element.context === action.todo.context){
                    flag = true; 
                }
            })
            if(flag){
                alert("不能重复添加todo！");
                return state;
            }
            state.todos.push(action.todo);
            localStorage.setItem("todo",JSON.stringify(state.todos));
            return{
                todos:[...state.todos],
                showTodo:[...state.todos]
            }
        // 选中
        case "CHANGESTATUS":
            state.todos.forEach((element)=>{
                if(element.context === action.todo.context){
                    element.status = action.checked?"FINISHED":"PENDDING"
                }
            })
            localStorage.setItem("todo",JSON.stringify(state.todos));
            return{
                todos:[...state.todos],
                showTodo:[...state.todos]
            }
        // 全部
        case "all":
            return{
                todos:[...state.todos],
                showTodo:[...state.todos]
            }
        // 未完成
        case "pendding":
            state.showTodo = [];
            state.todos.forEach(element => {
                if(element.status === "PENDDING"){
                    state.showTodo.push(element);
                }
            });
            return{
                todos:state.todos,
                showTodo:[...state.showTodo]
            }
        // 已完成
        case "finished":
            state.showTodo = [];
            state.todos.forEach(element => {
                if(element.status === "FINISHED"){
                    state.showTodo.push(element);
                }
            });
            return{
                todos:state.todos,
                showTodo:[...state.showTodo]
            }
        // 删除
        case "delete":
            var tempIndex1 = state.todos.findIndex((element)=>{
                return element.context === action.todo.context;
            })
            var tempIndex2 = state.showTodo.findIndex((element)=>{
                return element.context === action.todo.context;
            })
            if(tempIndex1!=-1){
                state.todos.splice(tempIndex1,1);
            }
            if(tempIndex2!=-1){
                state.showTodo.splice(tempIndex2,1);
            }
            // localStorage.setItem("todo",JSON.stringify(state.todos));
            return{
                todos:[...state.todos],
                showTodo:[...state.showTodo]
            }
        default:
            return state;
    }
}